package cs236369.hw5;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet({ "/UpdateProfile", "/UpdateProfile/*" })
public class UpdateProfile extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		PrintWriter out;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			response.setStatus(400);
			return;
		}
		if(session == null || session.getAttribute("userName") == null) {
			response.sendRedirect(request.getContextPath() + InitListener.welcomePage);
			return;
		}
		try {
			String username = (String)session.getAttribute("userName");
			User oldUser = DBConnection.getUserDetails(username);
			boolean isAdmin = oldUser.isAdmin();
			if(isAdmin == true && (request.getParameter("adminCheck") == null || !((String)request.getParameter("adminCheck")).equals("adminCheck"))) {
				// the user was admin, and not don't want to be an admin
				isAdmin = false;
				session.removeAttribute("admin");
			} else if(isAdmin == false && request.getParameter("adminPass") != null &&
					((String)request.getParameter("adminPass")).equals("I am an admin")) {
				isAdmin = true;
				session.setAttribute("admin", "admin");
			}
			User newUser = new User(username, request.getParameter("password"), request.getParameter("firstName"), request.getParameter("lastName"), 
					request.getParameter("email"), request.getParameter("phone"), isAdmin);
			DBConnection.updateUser(newUser);
		} catch (RescueMeException e) {
			response.setStatus(400);
			out.print(e.getMessage());
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
}
